package com.project.web.admin.service.core.impl;

import com.project.mapper.core.MenuMapper;
import com.project.mapper.core.RoleMenuMapper;
import com.project.model.core.Menu;
import com.project.web.admin.service.common.impl.BaseServiceImpl;
import com.project.web.admin.service.core.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service("menuServiceImpl")
public class MenuServiceImpl extends BaseServiceImpl<Menu, Long> implements MenuService {

    private static final long serialVersionUID = -6171964516679436627L;

    @Autowired
    private MenuMapper menuMapper;

    @Autowired
    private RoleMenuMapper roleMenuMapper;

    /**
     * 仅获取根节点
     */
    @Override
    public List<Menu> findOnlyRoots() {
        return menuMapper.findOnlyRoots();
    }

    /**
     * 普通用户 根据 资源类型、用户id
     * 查询菜单资源
     * 返回树形数据
     */
    @Override
    public List<Menu> findOrdinaryTreeMenu(Integer type, Long userId) {
        return getMenuTreeList(menuMapper.findOrdinaryMenu(type, userId));
    }

    /**
     * 普通用户 根据 用户id
     * 查询菜单资源
     * 返回行数据
     */
    @Override
    public List<Menu> findOrdinaryMenu(Long userId) {
        return menuMapper.findOrdinaryMenu(null, userId);
    }

    /**
     * 转化行数据结构为树形数据结构
     *
     * @param list
     * @return
     */
    public static List<Menu> getMenuTreeList(List<Menu> list) {

        List<Menu> nodeList = new ArrayList<Menu>();
        boolean mark;
        for (Menu node1 : list) {
            mark = false;
            for (Menu node2 : list) {
                if (node1.getParentId() != null && node1.getParentId().longValue() == node2.getId().longValue()) {
                    mark = true;
                    if (node2.getChildrens() == null) {
                        node2.setChildrens(new ArrayList<Menu>());
                    }
                    node2.getChildrens().add(node1);
                }
            }
            if (!mark) {
                nodeList.add(node1);
            }
        }
        return nodeList;
    }

    /**
     * 更具角色ID查询权限
     *
     * @param roleId
     * @return
     */
    @Override
    public List<Menu> selectMenusByRoleId(Long roleId) {
        return menuMapper.selectMenusByRoleId(roleId);
    }

    /**
     * 更具父级ID查询所有的子根节点
     *
     * @param parentId
     * @return
     */
    @Override
    public List<Menu> findChildrenNodes(Long parentId) {
        return menuMapper.findChildrenNodes(parentId);
    }


    /**
     * 覆盖deltete方法
     *
     * @param menuId
     * @return
     */
    @Override
    public int delete(Long menuId) {
        //首先解除role_menu的外键关联关系
        roleMenuMapper.deleteByMenuId(menuId);
        return super.delete(menuId);
    }
}
